<template>
  <div class="donee-page">
    <!-- 标题 -->
    <p class="title">
      <i class="el-icon-user"></i> 受捐赠人信息
    </p>
    <el-divider></el-divider>

    <!-- 搜索表单 和 添加按钮 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="searchForm.doneeId" placeholder="输入捐赠者 ID"></el-input>
      </el-form-item>
      <el-form-item label>
        <el-input size="small" v-model="searchForm.doneeName" placeholder="输入捐赠者姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addRow">添加</el-button>
        <el-button size="small" icon="el-icon-close" v-show="isSearch" @click="exitSearch">退出搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 受捐赠人表格 -->
    <el-table :data="doneeData" border highlight-current-row>
      <el-table-column prop="doneeId" label="受捐赠者 ID"></el-table-column>
      <el-table-column prop="doneeName" label="受捐赠者姓名"></el-table-column>
      <el-table-column prop="phoneNumber" label="电话号码"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="email" label="电子邮箱"></el-table-column>
      <el-table-column label="物资接收情况" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="info" @click="findSupplies(scope.row.doneeId)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row.doneeId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      background
      :total="totalRow"
      :current-page="currentPage"
      :page-sizes="[15, 30, 50, 100]"
      :page-size="pageSize"
      @current-change="currentChange"
      @size-change="sizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 编辑表单 -->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="doneeId" label="受捐赠者 ID">
          <el-input v-model="newRow.doneeId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="doneeName" label="受捐赠者姓名">
          <el-input v-model="newRow.doneeName"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话号码">
          <el-input v-model="newRow.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="newRow.address"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱">
          <el-input v-model="newRow.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditedRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加表单（和编辑表单基本相同） -->
    <el-dialog title="添加新的条目" :visible.sync="addFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="doneeId" label="受捐赠者 ID">
          <el-input v-model="newRow.doneeId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="doneeName" label="受捐赠者姓名">
          <el-input v-model="newRow.doneeName"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="电话号码">
          <el-input v-model="newRow.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="newRow.address"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱">
          <el-input v-model="newRow.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 查看某单位的接收捐赠情况 -->
    <el-dialog title="查看接收情况" :visible.sync="distributionTableVisible">
      <el-table :data="distributionTableData">
        <el-table-column prop="distributionId" label="物资 ID"></el-table-column>
        <el-table-column prop="doneeId" label="受捐赠人 ID"></el-table-column>
        <el-table-column prop="suppliesName" label="物资名称"></el-table-column>
        <el-table-column prop="type" label="种类"></el-table-column>
        <el-table-column prop="specifications" label="规格"></el-table-column>
        <el-table-column prop="units" label="单位"></el-table-column>
        <el-table-column prop="number" label="数量"></el-table-column>
        <el-table-column prop="distributeTime" label="分配时间"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      doneeData: [
        {
          doneeId: "",
          doneeName: "",
          phoneNumber: "",
          address: "",
          email: "",
        },
      ],
      searchForm: {
        doneeId: "",
        doneeName: "",
      },
      totalRow: 100,
      currentPage: 1,
      pageSize: 15,
      newRow: {
        doneeId: "",
        doneeName: "",
        phoneNumber: "",
        address: "",
        email: "",
      },
      rules: {
        phoneNumber: [{ required: true, message: "电话号码为必填项" }],
        email: [
          { required: true, message: "电子邮箱为必填项" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
      },
      distributionTableData: [
        {
          distributionId: "",
          doneeId: "",
          suppliesName: "",
          type: "",
          specifications: "",
          units: "",
          number: "",
          distributeTime: "",
        },
      ],
      editFormVisible: false,
      addFormVisible: false,
      distributionTableVisible: false,
      isSearch: false,
    };
  },
  computed: {
    totalPage() {
      return Math.ceil(this.totalRow / this.pageSize);
    },
  },
  methods: {
    // [GET] 通过 当前页 和 每页显示的条数 更新表格信息
    getData(currentPage, pageSize) {
      this.axios
        .get("/donee", {
          params: {
            currentPage: currentPage,
            pageSize: pageSize,
          },
        })
        .then((response) => {
          // 更新当前表格信息
          if (response.status === 200) {
            this.doneeData = response.data;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // [GET] 通过 捐赠者ID 和 捐赠者姓名 查找指定行
    search() {
      if (this.searchForm.doneeId === "" && this.searchForm.doneeName === "") {
        return false;
      }
      this.axios
        .get("/donee/search", {
          params: {
            doneeId: this.searchForm.doneeId,
            doneeName: this.searchForm.doneeName,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            this.isSearch = true;
            this.totalRow = response.data.totalRow;
            this.currentPage = 1;
            // 使用搜索结果更新表格
            this.getData(this.currentPage, this.pageSize);
          }
          // console.log(response);
        })
        .catch(() => {
          this.$message({
            message: "搜索失败",
            type: "error",
          });
        });
    },

    // 编辑按钮事件，初始化newRow，弹出编辑表单
    handleEdit(index, row) {
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = row[key];
      });
      this.editFormVisible = true;
    },

    // [PUT] 提交newRow，编辑条目，更新表格信息
    submitEditedRow(formName) {
      // console.log(this.newRow);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios
            .put("/donee/edit", JSON.stringify(this.newRow))
            .then((response) => {
              // console.log(response);
              if (response.status === 200) {
                this.getData(this.currentPage, this.pageSize); // 更新表格信息
                this.editFormVisible = false;
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
              }
            })
            .catch(() => {
              this.$message({
                message: "更新失败",
                type: "error",
              });
            });
        } else {
          return false;
        }
      });
    },

    // [delete] 删除表格中的一行信息
    handleDelete(index, id) {
      console.log(index, id);
      this.$confirm("确定删除该行？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.axios
          .delete("/donee/delete", {
            params: {
              doneeId: id,
            }
          })
          .then((response) => {
            // console.log(response);
            if (response.status === 200) {
              this.totalRow--;
              if (this.totalRow < this.currentPage * this.pageSize) {
                this.currentPage--;
              }
              this.getData(this.currentPage, this.pageSize); // 更新表格信息
              this.$message({
                message: "删除成功",
                type: "success",
              });
            }
          })
          .catch((error) => {
            this.$message({
              message: "删除失败",
              type: "error",
            });
            console.error(error);
          });
      })
      .catch(() => {
        return false;
      });
    },

    // 处理添加按钮，弹出添加信息表单
    addRow() {
      // 清空newRow
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = "";
      });
      this.addFormVisible = true;
    },

    // [POST] 提交newRow，添加新的条目，更新表格信息
    submitNewRow(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios
            .post("/donee/add", JSON.stringify(this.newRow))
            .then((response) => {
              // console.log(response);
              if (response.status === 200) {
                this.totalRow++;
                this.getData(this.currentPage, this.pageSize); // 更新表格信息
                this.addFormVisible = false;
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
              }
            })
            .catch(() => {
              this.$message({
                message: "更新失败",
                type: "error",
              });
            });
        } else {
          return false;
        }
      });
    },

    // 处理用户翻页
    currentChange(val) {
      this.currentPage = val;
      this.getData(this.currentPage, this.pageSize);
    },

    // 处理每页显示总条数的变化
    sizeChange(val) {
      this.pageSize = val;
      this.getData(this.currentPage, this.pageSize);
    },

    // [GET] 传递受捐赠人ID 获取该受捐赠人的被分配记录
    findSupplies(doneeId) {
      this.axios
        .get("/distribution/donee", {
          params: {
            doneeId: doneeId,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            this.distributionTableData = response.data;
            this.distributionTableVisible = true;
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message({
            message: "查看失败",
            type: "error",
          });
        });
    },
    exitSearch() {
      this.isSearch = false;
      this.searchForm.doneeId = "";
      this.searchForm.doneeName = "";
      this.axios
        .get("/donee/total")
        .then((response) => {
          if (response.status === 200) {
            this.totalRow = response.data.totalRow;
          }
        })
        .catch((error) => {
          console.error(error);
        });
      this.getData(this.currentPage, this.pageSize);
    },
  },
  created() {
    this.axios
      .get("/donee/total")
      .then((response) => {
        if (response.status === 200) {
          this.totalRow = response.data.totalRow;
        }
      })
      .catch((error) => {
        console.error(error);
      });
    this.getData(this.currentPage, this.pageSize);
  },
};
</script>

<style scoped>
.donee-page {
  text-align: left;
}

.title {
  margin: 5px 0 0 15px;
}

.user-search {
  padding-left: 15px;
}

.el-pagination {
  margin-top: 20px;
  margin-bottom: 30px;
}

.el-dialog__body {
  padding-right: 100px !important;
  padding-left: 50px !important;
}

.el-dialog__footer {
  padding: 0 100px 30px 30px !important;
}
</style>